package main

import (
	"context"
	"fmt"
	"github.com/kkdai/youtube/v2"
	"io"
	"io/ioutil"
	"log"
	"net/http"
	"os"
	"strings"
	"time"
)

func main() {
	//os.Setenv("all_proxy", "socks5://127.0.0.1:1081")
	//os.Setenv("http_proxy", "http://127.0.0.1:8001")

	resp1, err := http.Get("http://ipinfo.io")
	if err != nil {
		panic(err)
	}
	defer resp1.Body.Close()

	body, err := ioutil.ReadAll(resp1.Body)
	if err != nil {
		panic(err)
	}

	fmt.Println(string(body))
	//videoID := "aEOHGmYzG84"

	client := youtube.Client{}

	video, err := client.GetVideoContext(context.Background(), "https://www.youtube.com/watch?v=aEOHGmYzG84")
	if err != nil {
		log.Fatalf("Error GetVideoContext: %v", err)
	}
	fmt.Printf("GetVideoContext:%v \n", *video)

	selectedFormat := &youtube.Format{}
	formats := (*video).Formats
	//var selectedFormat youtube.Format
	// 遍历格式信息，找到所需的格式
	for _, format := range formats {
		if format.ItagNo == 22 { // 22 表示 720p MP4 格式
			selectedFormat = &format
			break
		}
	}
	fmt.Println("selectedFormat:%v", *selectedFormat)

	if err != nil {
		panic(err)
	}
	stream, err := client.GetStreamURL(video, selectedFormat)
	if err != nil {
		log.Fatalf("Error getting video stream: %v", err)
	}

	// 创建一个 HTTP 客户端并获取视频流
	resp, err := http.Get(stream)
	if err != nil {
		log.Fatalf("Error getting video stream: %v", err)
	}
	defer resp.Body.Close()

	// 创建一个文件来保存视频
	filename := fmt.Sprintf("%s_%s.mp4", time.Now().Format("20060102"), strings.ToLower(selectedFormat.AudioQuality))
	file, err := os.Create(filename)
	if err != nil {
		log.Fatalf("Error creating file: %v", err)
	}
	defer file.Close()

	fmt.Printf("start save to file")
	// 将视频流复制到文件
	_, err = io.Copy(file, resp.Body)
	if err != nil {
		log.Fatalf("Error saving video: %v", err)
	}

	fmt.Printf("Video saved to %s\n", filename)

}
